﻿/* Muaz Khan – http://dashingquill.web.officelive.com */
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Syndication;
using System.Web.Mvc;
using System.Xml;
using DTweet.Models;

namespace DTweet.Helpers
{
    public class RssResult : FileResult
    {
        public List<Tweet> Tweets { get; set; }
        public string Title { get; set; }
        private readonly DatabaseEntities _db;

        private Uri _currentUrl;

        public RssResult() : base("application/rss+xml") { }

        public RssResult(List<Tweet> tweets, string title, DatabaseEntities db)
            : this()
        {
            Tweets = tweets.OrderByDescending(t => t.Id).Take(10).ToList();
            Title = title;
            _db = db;
        }       

        public override void ExecuteResult(ControllerContext context)
        {
            _currentUrl = context.RequestContext.HttpContext.Request.Url;
            Static.Domain = _currentUrl.Scheme + "://" + _currentUrl.Host + "/";
            base.ExecuteResult(context);
        }
        protected override void WriteFile(System.Web.HttpResponseBase response)
        {
            var items = (from tweet in Tweets
                         let contentString = String.Format("{0} by {1} on {2:MMM dd, yyyy}", tweet.Message.ReplaceAll().HandlePreLineBreak(), tweet.UserToken.GetAccountByUserToken(_db).FullName, tweet.TweetingTime)
                         select new SyndicationItem(
                             title: tweet.Message.FetchTitle(), 
                             content: contentString,
                             itemAlternateLink: new Uri(Static.Domain + tweet.TweetToken + "/" + tweet.Message.FetchPostUrl()),
                             id: Static.Domain + tweet.TweetToken + "/" + tweet.Message.FetchPostUrl(), 
                             lastUpdatedTime: tweet.TweetingTime.ToUniversalTime())
                                    {
                                        PublishDate = tweet.TweetingTime.ToUniversalTime(), 
                                        Summary = new TextSyndicationContent(contentString, TextSyndicationContentKind.Plaintext)
                                    }).ToList();

            var feed = new SyndicationFeed(
                Title,
                Title, /* Using Title also as Description */
                _currentUrl,
                items);          

            var formatter = new Rss20FeedFormatter(feed);

            using (var writer = XmlWriter.Create(response.Output))
            {
                formatter.WriteTo(writer);
            }

        }
    }
}